import hashlib
import os
import tempfile
from concurrent.futures import ThreadPoolExecutor

from utils.log_util import get_logger


class ImageProcessorModel:
    """图片处理器数据模型"""

    def __init__(self, config_manager):
        self.config_manager = config_manager
        self.dropped_files = []
        self.preview_images = []

        # 初始化配置
        self.config = self._load_config()

        # 缩略图缓存目录
        self.thumbnail_cache_dir = os.path.join(tempfile.gettempdir(), "image_tool_thumbnails")
        os.makedirs(self.thumbnail_cache_dir, exist_ok=True)

        # 线程池
        self.executor = ThreadPoolExecutor(max_workers=4)
        self.preview_futures = []

        self.logger = get_logger()

    def _load_config(self):
        """从配置管理器加载配置"""
        config = self.config_manager.load_config()
        return {
            "work_dir": config.get("work_image_tool", {}).get("work_dir", ""),
            "folder_name": config.get("work_image_tool", {}).get("folder_name", ""),
            "template_path": config.get("work_image_tool", {}).get("template_path", ""),
        }

    def save_config(self, work_dir, folder_name, template_path):
        """保存配置到配置管理器"""
        current_config = {
            "work_dir": work_dir,
            "folder_name": folder_name,
            "template_path": template_path,
        }
        config = self.config_manager.load_config()
        config["work_image_tool"] = current_config
        self.config_manager.update_config(config)
        self.config = current_config

    def get_thumbnail_path(self, file_path):
        """根据原图路径生成唯一缩略图缓存路径"""
        hash_str = hashlib.md5(file_path.encode()).hexdigest()
        filename = f"{hash_str}.jpg"
        return os.path.join(self.thumbnail_cache_dir, filename)

    def get_original_path(self, compressed_path):
        """获取压缩图片对应的原始路径"""
        meta_path = compressed_path + '.meta'
        if os.path.exists(meta_path):
            with open(meta_path, 'r') as f:
                return f.read().strip()
        return compressed_path